import { defineStore } from "pinia"
import { ref } from "vue"

export const useUserStore = defineStore('user', () => {
	const userInfo = ref(null)
	
	// 获取存储openID
	const openIDStorage = async () => {
		try{
			const res = await uni.getStorage({
				key: 'CPuser'
			})
			return res.data.openid
		}catch{
			console.log('本地没有openID');
			return ''
		}
	}
	
	
	//获取openID
	const getOpenID = async () => {
		// 拿到到登录code
		const loginResult  = await uni.login({
			provider: 'weixin'
		})
		const code = loginResult.code
		// 通过code获取微信openID
		const userOpenId = await uniCloud.callFunction({
			name: 'get-openID',
			data: { code }
		})
		console.log('Store.openID:', userOpenId.result)
		return userOpenId.result
	}
	// 获取openID后注册用户信息
	const Login = async (userInfo) => {
		const _openID = await getOpenID()
		// 通过openID获取用户信息
		const _user = await uniCloud.callFunction({
			name: 'login',
			data: { userInfo, openid: _openID}
		})
		await uni.setStorage({
			data: { openid: _openID },
			key: 'CPuser'
		})
		// userInfo.value = _user.result.data
		console.log('Store.userInfo:', _user.result.data)
	}
	// 获取用户信息
	const getUserInfo = async (openID) => {
		let _openID = ''
		if(openID){
			_openID = openID
		}else{
			_openID = await getOpenID()
		}
		const _user = await uniCloud.callFunction({
			name: 'get-userInfo',
			data: { openid: _openID }
		})
		// console.log('userInfo:', _user.result.data)
		return _user.result.data[0]
	}
	
	return { getOpenID, Login, openIDStorage, userInfo, getUserInfo }
})